package com.thghh.fsbrowser.fs;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;

/**
 * com.thghh.fsbrowser.fs.FSOutputStream
 * 
 * @author Zhikang.Peng
 * @date 2018-09-2616:30:05
 * @since 1.0
 */
public class FSOutputStream extends OutputStream {

	OutputStream wrappedStream;
	IFileSystem fs;
	boolean closed;
	long pos;
	
	public FSOutputStream(FilePath fp) throws IOException {
		this(fp.fs().create(fp), fp.fs());
	}

	FSOutputStream(OutputStream stream, IFileSystem fs) {
		if (stream == null) {
			throw new IllegalArgumentException("Null InputStream");
		}
		if (fs == null) {
			throw new IllegalArgumentException("FTP client null or not connected");
		}
		this.wrappedStream = stream;
		this.fs = fs;
		this.pos = 0;
		this.closed = false;
	}

	public long getPos() {
		return pos;
	}

	@Override
	public void write(int b) throws IOException {
		if (closed) {
			throw new IOException("Stream closed");
		}
		wrappedStream.write(b);
		pos++;
	}

	@Override
	public void write(byte[] buf, int off, int len) throws IOException {
		if (closed) {
			throw new IOException("Stream closed");
		}
		wrappedStream.write(buf, off, len);
		pos += len;
	}

	@Override
	public void flush() throws IOException {
		wrappedStream.flush();
		super.flush();
	}

	@Override
	public void close() throws IOException {
		if (closed) {
			throw new IOException("Stream closed");
		}
		wrappedStream.close();
		super.close();
		closed = true;
		if (!fs.isConnected()) {
			throw new ConnectException("fs not connected");
		}
		fs.close();
	}

}
